package slh.commentVote;


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet(name = "CommentVoteServlet", value = "/comment-vote")
public class commentVoteServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String action = request.getParameter("action");
        String commentIdStr = request.getParameter("commentId");
        String userId = (String) request.getSession().getAttribute("userId");

        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.print("{\"error\":\"请先登录\"}");
            return;
        }

        if (commentIdStr == null || action == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"error\":\"参数不完整\"}");
            return;
        }

        try {
            int commentId = Integer.parseInt(commentIdStr);
            commentVoteDao voteDao = new commentVoteDao();
            boolean success;

            switch (action) {
                case "upvote":
                    success = voteDao.addVote(commentId, userId, 1);
                    break;
                case "downvote":
                    success = voteDao.addVote(commentId, userId, -1);
                    break;
                case "remove":
                    success = voteDao.removeVote(commentId, userId);
                    break;
                default:
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    out.print("{\"error\":\"无效的操作类型\"}");
                    return;
            }

            if (success) {
                int[] voteCounts = voteDao.getVoteCounts(commentId);
                Integer userVote = voteDao.getUserVote(commentId, userId);

                out.print(String.format("{\"success\":true,\"upVotes\":%d,\"downVotes\":%d,\"userVote\":%s}",
                        voteCounts[0], voteCounts[1], userVote != null ? userVote : "null"));
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.print("{\"error\":\"操作失败\"}");
            }
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"error\":\"评论ID格式错误\"}");
        } catch (SQLException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print("{\"error\":\"数据库错误\"}");
            e.printStackTrace();
        }
    }
}
